package com.hqd.jjvm.classformat;

import com.hqd.jjvm.classpath.ClassFileInfo;
import lombok.Getter;

/**
 * @author hqd
 * 基础class信息
 */
@Getter
public abstract class AbstractClassCode {
    private ClassFileInfo classFileInfo;
    private String hexStr;

    public AbstractClassCode(ClassFileInfo classFileInfo) {
        this.classFileInfo = classFileInfo;
        this.hexStr = classFileInfo.getByteCode();
    }

    /**
     * 是否以只读的方式（不移动指针），读取指定长度字节
     *
     * @param length
     * @param isReadOnly
     * @return
     */
    public String read(int length, boolean isReadOnly) {
        String str = this.hexStr.substring(0, length << 1);
        if (!isReadOnly) {
            this.hexStr = this.hexStr.substring(length << 1);
        }
        return str;
    }

    /**
     * 读取指定长度字节
     *
     * @param length
     * @return
     */
    public String read(int length) {
        return read(length, false);
    }

    /**
     * 读取1个字节
     *
     * @return
     */
    public String readU1() {
        return read(1);
    }

    /**
     * 读取2个字节
     *
     * @return
     */
    public String readU2() {
        return read(2);
    }

    /**
     * 读取4个字节
     *
     * @return
     */
    public String readU4() {
        return read(4);
    }

    /**
     * 读取8个字节
     *
     * @return
     */
    public String readU8() {
        return read(8);
    }
}
